package com.jbp.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jbp.dao.WalletTransferDao;
import com.jbp.exception.RRException;
import com.jbp.model.*;
import com.jbp.service.*;
import com.jbp.utils.PageUtils;
import com.jbp.utils.Query;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Date;
import java.util.Map;

/**
 * 红包转账记录(WalletTransfer)表服务实现类
 * @author cc
 * @since 2020-07-01 10:28:15
 */
@Service
public class WalletTransferServiceImpl extends ServiceImpl<WalletTransferDao, WalletTransfer> implements WalletTransferService {
    @Autowired
    private WalletService walletService;
    @Autowired
    private WalletRecordService walletRecordService;

    @Autowired
    private RankProportionService rankProportionService;


    @Autowired
    private UserService userService;
    @Autowired
    private TecentMsgService tecentMsgService;
    @Autowired
    private PropertyService propertyService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<WalletTransfer> queryWrapper = new QueryWrapper<>();
        if (params.get("id") != null){
            queryWrapper.like("id",params.get("id"));
        }
        IPage<WalletTransfer> page = this.page(
                new Query<WalletTransfer>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    /**红包转账*/
    @Override
    @Transactional
    public synchronized void transfer(Integer userId, WalletTransfer req) {
        //检查余额
        Wallet wallet = walletService.getByUserId(userId);
        if (wallet == null) {
            throw new RRException("用户数据异常");
        }
        if (wallet.getXinzuan().intValue()<=0) {
            throw new RRException("请求数据异常");
        }
        if (wallet.getXinzuan().compareTo(req.getNum()) <0 ) {
            throw new RRException("心钻余额不足");
        }
        User user = userService.getById(userId);
        if (!"yes".equalsIgnoreCase(user.getTransfer()) && !"1".equals(propertyService.getV("auto_transfer"))) {
            throw new RRException("账号异常");
        }

        //增加转账
        WalletTransfer walletTransfer = new WalletTransfer();
        walletTransfer.setNum(req.getNum());
        walletTransfer.setFromUserId(userId);
        walletTransfer.setToUserId(req.getToUserId());
        save(walletTransfer);

        //发送方心钻变动记录
        WalletRecord walletRecordFrom = new WalletRecord();
        walletRecordFrom.setUserId(userId);
        walletRecordFrom.setAddType("sub");
        walletRecordFrom.setCoinType("xinzuan");
        walletRecordFrom.setOperationType("hbout");
        walletRecordFrom.setBeforeBalance(wallet.getXinzuan());
        walletRecordFrom.setChangeBalance(req.getNum());
        walletRecordFrom.setAfterBalance(wallet.getXinzuan().subtract(req.getNum()));
        walletRecordService.save(walletRecordFrom);

        //百万奖池金额处理
        rankProportionService.addPrizePoolAmount(walletRecordFrom.getChangeBalance());

        //发送方修改钱包余额
        wallet.setXinzuan(wallet.getXinzuan().subtract(req.getNum()));
        walletService.updateWithLock(wallet);

        //接受方心钻变动记录
        Wallet toWallet = walletService.getByUserId(req.getToUserId());
        WalletRecord walletRecordTo = new WalletRecord();
        walletRecordTo.setUserId(req.getToUserId());
        walletRecordTo.setAddType("add");
        walletRecordTo.setCoinType("xinzuan");
        walletRecordTo.setOperationType("hbin");
        walletRecordTo.setBeforeBalance(toWallet.getXinzuan());
        walletRecordTo.setChangeBalance(req.getNum());
        walletRecordTo.setAfterBalance(toWallet.getXinzuan().add(req.getNum()));
        walletRecordService.save(walletRecordTo);

        //接受方修改钱包余额
        toWallet.setXinzuan(toWallet.getXinzuan().add(req.getNum()));
        walletService.updateWithLock(toWallet);

        boolean result = sendTransferMsg(userId, req.getToUserId(), req.getNum());
        if (!result) {
            throw new RRException("发送失败");
        }
    }

    /**发送红包消息*/
    public boolean sendTransferMsg(Integer fromUserId, Integer toUserId, BigDecimal xinzuan){
        String msg = "-#*hongbao*#-"+xinzuan.toString()+"-#*hongbao*#-恭喜发财，大吉大利";
        return tecentMsgService.sendMsg(fromUserId.toString(), toUserId.toString(), msg);
    }
}
